package com.jiangcheng.demo.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.List;


@ServerEndpoint("/user/{id}")
@Component
public class PrivateLetter {
    static PrivateLetterManager privateLetterManager;

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id, EndpointConfig config) throws IOException {
        /**
         * 判断是否创建了这个管理器
         */
        if (privateLetterManager == null) {
            privateLetterManager = new PrivateLetterManager();
        }
        privateLetterManager.addClient(id, session);
        /**
         * 判断是否有离线消息
         */
        privateLetterManager.is_offline(id);
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        System.out.println(message);
        /**
         *  对消息进行转成消息对象
         */
        System.out.println("有消息进来");

        WebSocketMessageEntity messageEntity = JSON.parseObject(message, WebSocketMessageEntity.class);
        System.out.println(messageEntity);
        // 判断是否为群聊
        if (messageEntity != null) {
            // 给目标人发送私信
            privateLetterManager.sendMessage(messageEntity, session, messageEntity.getAction());
        }


    }

    @OnClose
    public void onClose(@PathParam("id") String id, Session session, CloseReason closeReason) throws IOException {
        // 移除客户端
        privateLetterManager.remove(id);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("连接发生错误");
        Error error = new Error();
        error.printStackTrace();
    }


}
